import { CreepRoles } from '../structures/spawn/types'

/**
 * 清理过期爬虫记忆
 */
export function clearCreepMemory() {
    global.roleStats = {}

    // 清理memory
    for (const creepName in Memory.creeps) {
        const creep = Game.creeps[creepName]
        if (!creep) {
            delete Memory.creeps[creepName]
            continue
        }

        // 统计房间角色数量
        const roomName = creep.memory.belong
        if (!global.roleStats[roomName]) global.roleStats[roomName] = {}

        const roleCreepNames = global.roleStats[roomName][creep.memory.role]
        if (!roleCreepNames) {
            global.roleStats[roomName][creep.memory.role] = [creep]
        } else {
            roleCreepNames.push(creep)
        }
    }
}

/**
 * 获取指定房间指定角色的爬虫列表
 */
export function getRoleCreeps(roomName: string, role: CreepRoles): Creep[] {
    if (!global.roleStats[roomName]) return []
    return global.roleStats[roomName][role] || []
}

/**
 * 清理过期房间记忆
 */
export function clearRoomMemory() {
    if (Game.time % 511) return
    for (const roomName in Memory.rooms) {
        const room = Game.rooms[roomName]
        if (
            (!room || !room.controller?.my) &&
            // @ts-ignore
            (!Memory?.rooms?.[roomName]?.lastUpdate || Game.time - Memory?.rooms?.[roomName]?.lastUpdate > 1500)
        ) {
            delete Memory.rooms[roomName]
        }
    }
}

/**
 * 清理过期旗帜记忆
 */
export function clearFlagMemory() {
    if (Game.time % 511) return
    for (const flagName in Memory.flags) {
        const flag = Game.flags[flagName]
        if (!flag) {
            delete Memory.flags[flagName]
        }
    }
}

/**
 * 清理过期全局记忆
 */
export function clearGlobalMemory() {
    if (!Memory.tempBypassRooms) Memory.tempBypassRooms = {}

    for (const roomName in Memory.tempBypassRooms) {
        if (Memory.tempBypassRooms[roomName] < Game.time) {
            delete Memory.tempBypassRooms[roomName]
        }
    }
}
